package gdufs.lkl.calculator;

import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

/**
 * 简单的设置界面
 */
public class SettingsActivity extends AppCompatActivity {
    
    private SettingsManager settingsManager;
    
    private EditText editDecimalPlaces;
    private EditText editHistoryMaxCount;
    private Button btnRestoreDefaults;
    private Button btnSaveSettings;
    private TextView tvCurrentSettings;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_settings);
        setSupportActionBar(findViewById(R.id.toolbar));
        // 设置标题栏
        if (getSupportActionBar() != null) {
            getSupportActionBar().setTitle("设置");
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        }
        
        // 初始化设置管理器
        settingsManager = SettingsManager.getInstance(this);
        
        // 初始化视图
        initViews();
        
        // 加载当前设置
        loadCurrentSettings();
        
        // 设置监听器
        setupListeners();
        
        // 更新当前设置显示
        updateCurrentSettingsDisplay();
    }
    
    private void initViews() {
        editDecimalPlaces = findViewById(R.id.editDecimalPlaces);
        editHistoryMaxCount = findViewById(R.id.editHistoryMaxCount);
        btnRestoreDefaults = findViewById(R.id.btnRestoreDefaults);
        btnSaveSettings = findViewById(R.id.btnSaveSettings);
        tvCurrentSettings = findViewById(R.id.tvCurrentSettings);
    }
    
    private void loadCurrentSettings() {
        editDecimalPlaces.setText(String.valueOf(settingsManager.getDecimalPlaces()));
        editHistoryMaxCount.setText(String.valueOf(settingsManager.getHistoryMaxCount()));
    }
    
    private void setupListeners() {
        btnSaveSettings.setOnClickListener(v -> saveSettings());
        btnRestoreDefaults.setOnClickListener(v -> showRestoreDefaultsDialog());
    }
    
    private void saveSettings() {
        try {
            // 保存小数位数设置
            String decimalText = editDecimalPlaces.getText().toString().trim();
            if (!decimalText.isEmpty()) {
                int decimalPlaces = Integer.parseInt(decimalText);
                if (decimalPlaces >= 0 && decimalPlaces <= 15) {
                    settingsManager.setDecimalPlaces(decimalPlaces);
                } else {
                    Toast.makeText(this, "小数位数必须在0-15之间", Toast.LENGTH_SHORT).show();
                    return;
                }
            }
            
            // 保存历史记录最大条数设置
            String historyText = editHistoryMaxCount.getText().toString().trim();
            if (!historyText.isEmpty()) {
                int historyMaxCount = Integer.parseInt(historyText);
                if (historyMaxCount >= 10 && historyMaxCount <= 1000) {
                    settingsManager.setHistoryMaxCount(historyMaxCount);
                } else {
                    Toast.makeText(this, "历史记录条数必须在10-1000之间", Toast.LENGTH_SHORT).show();
                    return;
                }
            }
            
            // 更新显示
            updateCurrentSettingsDisplay();
            
            Toast.makeText(this, "设置已保存", Toast.LENGTH_SHORT).show();
            
        } catch (NumberFormatException e) {
            Toast.makeText(this, "请输入有效的数字", Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            Toast.makeText(this, "保存设置失败：" + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }
    
    private void showRestoreDefaultsDialog() {
        new AlertDialog.Builder(this)
            .setTitle("恢复默认设置")
            .setMessage("确定要恢复所有默认设置吗？\n小数位数：10位\n历史记录：100条")
            .setPositiveButton("确定", (dialog, which) -> {
                settingsManager.restoreDefaults();
                loadCurrentSettings();
                updateCurrentSettingsDisplay();
                Toast.makeText(this, "已恢复默认设置", Toast.LENGTH_SHORT).show();
            })
            .setNegativeButton("取消", null)
            .show();
    }
    
    private void updateCurrentSettingsDisplay() {
        String currentSettings = String.format("当前设置：小数位数 %d位，历史记录 %d条",
                settingsManager.getDecimalPlaces(),
                settingsManager.getHistoryMaxCount());
        tvCurrentSettings.setText(currentSettings);
    }
    
    @Override
    public boolean onSupportNavigateUp() {
        onBackPressed();
        return true;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        int id = item.getItemId();

        if (id == android.R.id.home) {
            finish();
            return true;
        } else if (id == R.id.action_switch_to_calculator) {
            Intent intent = new Intent(this, MainActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
            finish();
            return true;
        } else if (id == R.id.action_switch_to_scientific) {
            Intent intent = new Intent(this, ScientificCalculatorActivity.class);
            startActivity(intent);
            finish();
            return true;
        } else if (id == R.id.action_switch_to_converter) {
            Intent intent = new Intent(this, ConverterActivity.class);
            startActivity(intent);
            finish();
            return true;
        } else if (id == R.id.action_custom_function) {
            Intent intent = new Intent(this, CustomFunctionManagerActivity.class);
            startActivity(intent);
            return true;
        } else if (id == R.id.action_history) {
            Intent intent = new Intent(this, HistoryActivity.class);
            startActivity(intent);
            return true;
        } else if (id == R.id.action_settings) {
            Intent intent = new Intent(this, SettingsActivity.class);
            startActivity(intent);
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}
